<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :visible="visible"
    :destroyOnClose="true"
    :width="600"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeModal"
  >
    <div class="header-box">
      <!--  头像  -->
      <a-avatar v-if="detail.avatar" :size="56" :src="detail.avatar">
      </a-avatar>
      <a-avatar v-else :size="56" class="bg-primary">
        {{ getName(detail.realname) }}
      </a-avatar>
      <!--  描述  -->
      <div class="header-dec">
        <div>
          <span class="dec-name">{{ detail.realname }}</span>
          <a-tag
            :color="
              detail.status === 1
                ? '#87d068'
                : detail.status === 3
                ? '#faad14'
                : '#87d068'
            "
          >
            {{
              detail.status === 1 ? "正常" : detail.status === 3 ? "未激活" : ""
            }}
          </a-tag>
        </div>
        <div class="dec-gray">工号：{{ detail.job_number }}</div>
      </div>
    </div>
    <!--  tabs  start-->
    <a-tabs v-model:activeKey="activeKey" class="mb-10" :tabBarStyle="{borderBottom:'1px solid #f0f0f0'}">
      <a-tab-pane v-for="item of infoTabs" :key="item.key" :tab="item.title">
      </a-tab-pane>
    </a-tabs>
    <!--  tabs  end-->
    <a-form layout="vertical" key="edit_content">
      <!--   基本信息  start   -->
      <a-form-item
        label="成员姓名"
        v-bind="validateInfos.realname"
        v-show="activeKey === 'basic'"
      >
        <a-input
          placeholder="请输入成员姓名"
          v-model:value="modelRef.realname"
          :maxlength="10"
          v-if="modalType === 'edit'"
        />
        <span v-else>
          {{ modelRef.realname || "--" }}
        </span>
      </a-form-item>
      <a-form-item
        label="工号"
        v-bind="validateInfos.job_number"
        v-show="activeKey === 'basic'"
      >
        <a-input
          placeholder="请输入员工工号"
          v-model:value="modelRef.job_number"
          v-if="modalType === 'edit'"
        />
        <span v-else>
          {{ modelRef.job_number || "--" }}
        </span>
      </a-form-item>

      <a-form-item
        label="手机号码"
        v-bind="validateInfos.phone"
        v-show="activeKey === 'basic'"
      >
        <a-input
          :disabled="id ? true : false"
          :addon-before="modelRef.phone_country"
          placeholder="请输入成员手机号码"
          v-model:value="modelRef.phone"
          v-if="modalType === 'edit'"
        />
        <span v-else>
          {{ modelRef.phone || "--" }}
        </span>
      </a-form-item>
      <a-form-item label="邮箱地址" v-show="activeKey === 'basic'">
        <a-input
          v-if="modalType === 'edit'"
          placeholder="请输入邮箱地址"
          v-model:value="modelRef.email"
        />
        <span v-else>
          {{ modelRef.email || "--" }}
        </span>
      </a-form-item>
      <a-form-item label="工作电话" v-show="activeKey === 'basic'">
        <a-input
          placeholder="请输入工作电话"
          v-model:value="modelRef.work_phone"
          v-if="modalType === 'edit'"
        />
        <span v-else>
          {{ modelRef.work_phone || "--" }}
        </span>
      </a-form-item>
      <a-form-item
        label="成员头像"
        v-bind="validateInfos.avatar"
        v-show="
          activeKey === 'basic' &&
          ((modalType === 'view' && modelRef.avatar) || modalType === 'edit')
        "
      >
        <a-upload
          :action="imgAction"
          :headers="{ 'org-token': $store.getters.token }"
          :multiple="false"
          v-model:file-list="fileList"
          @change="handleUploadChange"
          name="image"
          :data="{ dir: 'org_personal' }"
          accept="image/jpg,image/jpeg,image/gif,image/png"
          list-type="picture-card"
          :disabled="modalType === 'view'"
        >
          <div v-if="fileList.length < 1">
            <PlusOutlined />
            <div style="padding-top: 4px">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <!--   基本信息  end   -->
      <!--   工作信息  start   -->
      <a-form-item
        label="入职时间"
        v-bind="validateInfos.induction_time"
        v-show="activeKey === 'work'"
      >
        <a-date-picker
          v-model:value="modelRef.induction_time"
          type="date"
          placeholder="请选择入职时间"
          style="width: 100%"
          v-if="modalType === 'edit'"
        />
        <span v-else>
          {{
            modelRef.induction_time
              ? modelRef.induction_time.format("YYYY-MM-DD")
              : "--"
          }}
        </span>
      </a-form-item>

      <a-form-item
        label="所属角色"
        v-if="isAdmin()"
        v-show="activeKey === 'work'"
      >
        <a-select
          placeholder="请选择角色"
          :options="roleList"
          v-model:value="modelRef.role_id"
          v-if="modalType === 'edit'"
          :disabled="disabledAdmin()"
        />
        <span v-else>
          {{ getMemberRole(modelRef.role_id) || "--" }}
        </span>
      </a-form-item>

      <a-form-item
        label="所属部门"
        v-bind="validateInfos.department"
        v-show="activeKey === 'work'"
      >
        <TreeSelect
          v-model:value="modelRef.department"
          :tree-data="departmentTreeData"
          allow-clear
          multiple
          placeholder="请选择成员所属部门"
          v-if="modalType === 'edit'"
        ></TreeSelect>
        <div v-else>
          <div v-if="departmentLabelArr.length">
            <a-tag
              v-for="(item, index) of departmentLabelArr"
              :key="index"
              color="processing"
              style="margin-bottom: 4px"
              >{{ item }}</a-tag
            >
          </div>
          <span v-else>--</span>
        </div>
      </a-form-item>

      <a-form-item label="直属上级" v-show="activeKey === 'work'">
        <template v-if="modalType === 'edit'">
          <a-tag
            v-if="selectedMember"
            :closable="true"
            @close="handleTagClose"
            color="processing"
          >
            {{ selectedMember.realname }}
          </a-tag>
          <a-button type="primary" shape="circle" @click="chooseMember">
            <template #icon><EditOutlined /></template>
          </a-button>
        </template>
        <span v-else>
          {{ selectedMember ? selectedMember.realname : "--" }}
        </span>
      </a-form-item>

      <a-form-item
        label="职位"
        v-bind="validateInfos.position"
        v-show="activeKey === 'work'"
      >
        <a-input
          placeholder="请输入成员职位"
          v-model:value="modelRef.position"
          v-if="modalType === 'edit'"
        />
        <span v-else>
          {{ modelRef.position || "--" }}
        </span>
      </a-form-item>
      <a-form-item
        label="职称"
        v-bind="validateInfos.work_name"
        v-show="activeKey === 'work'"
      >
        <a-input
          placeholder="请输入职称"
          v-model:value="modelRef.work_name"
          v-if="modalType === 'edit'"
        />
        <span v-else>
          {{ modelRef.work_name || "--" }}
        </span>
      </a-form-item>
      <!--   工作信息  end   -->
      <!--   个人信息  start   -->
      <a-form-item
        label="成员性别"
        v-bind="validateInfos.gender"
        v-show="activeKey === 'person'"
      >
        <a-radio-group
          :options="genderOptions"
          v-model:value="modelRef.gender"
          v-if="modalType === 'edit'"
        />
        <span v-else>
          {{ getMemberGender(modelRef.gender) || "--" }}
        </span>
      </a-form-item>
      <a-form-item
        label="出生年月"
        v-bind="validateInfos.birthday"
        v-show="activeKey === 'person'"
      >
        <a-date-picker
          v-model:value="modelRef.birthday"
          type="date"
          placeholder="请选择出生年月"
          style="width: 100%"
          v-if="modalType === 'edit'"
        />
        <span v-else>
          {{
            modelRef.birthday ? modelRef.birthday.format("YYYY-MM-DD") : "--"
          }}
        </span>
      </a-form-item>
      <a-form-item label="政治面貌" v-show="activeKey === 'person'">
        <a-select
          placeholder="请选择政治面貌"
          :options="politicalOptions"
          v-model:value="modelRef.political_type"
          v-if="modalType === 'edit'"
        />
        <span v-else>
          {{
            modelRef.political_type
              ? getPolitical(modelRef.political_type)
              : "--"
          }}
        </span>
      </a-form-item>
      <a-form-item
        label="成员人脸照片"
        v-show="activeKey === 'person'"
      >
        <a-upload
          v-if="((modalType === 'view' && modelRef.face_image) || modalType === 'edit')"
          :action="imgAction"
          :headers="{ 'org-token': $store.getters.token }"
          :multiple="false"
          v-model:file-list="filefaceImage"
          @change="handleUploadFaceChange"
          name="image"
          :data="{ dir: 'org_personal' }"
          accept="image/jpg,image/jpeg,image/gif,image/png"
          list-type="picture-card"
          :disabled="modalType === 'view'"
        >
          <div v-if="filefaceImage.length < 1">
            <PlusOutlined />
            <div style="padding-top: 4px">上传</div>
          </div>
        </a-upload>
        <div v-else>--</div>
      </a-form-item>
      <!--   个人信息  end   -->
    </a-form>
    <div v-if="canEdit && modalType === 'view'" class="drawer-footer">
      <a-button type="primary" @click.prevent="toEdit">去编辑</a-button>
    </div>
    <div v-if="modalType === 'edit'" class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
    </div>
    <ChooseOrgMember
      :visible="chooseMemberVisible"
      :getDetail="true"
      :deptDisabled="true"
      :uMax="1"
      @request="$utils.commonRequest"
      @close="closeChooseMemberModal"
      @success="handleMemberSelect"
    />
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import { Form, message, TreeSelect } from "ant-design-vue";
import moment, { Moment } from "moment";
import _ from "lodash";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";
import { ChooseOrgMember } from "bl-common-vue3";
import { EditOutlined, PlusOutlined } from "@ant-design/icons-vue";
import store from "../../../../store";

const useForm = Form.useForm;

export default defineComponent({
  name: "EditMember",
  components: { TreeSelect, EditOutlined, ChooseOrgMember, PlusOutlined },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
    type: {
      type: String,
      default: "",
    },
    canEdit: {
      type: Boolean,
      default: true,
    },
  },
  setup(props, context) {
    const { post, put, get } = request;
    /**
     * @description: 标题显示
     */
    const title = computed(() => {
      return props.id
        ? props.type == "view"
          ? "成员详情"
          : "编辑成员"
        : "新增成员";
    });

    const isAdmin = () => {
      return store.getters.userInfo.level == 99;
    };

    const disabledAdmin = () => {
      return (
        store.getters.userInfo.admin_uid == modelRef.uid ||
        store.getters.userInfo.uid == modelRef.uid
      );
    };

    const departmentTreeData = ref([]);

    // ""添加 "edit"编辑 "view"查看
    const modalType = ref("");
    watch(
      () => props.type,
      (val) => {
        modalType.value = val;
      }
    );

    /**
     * @description: 触发关闭
     */
    const closeModal = () => {
      if (props.type == "view" && modalType.value == "edit") {
        // 从详情跳进来的点取消应该返回查看详情
        getEditInfo().then(() => {
          modalType.value = "view";
        });
        return;
      }
      context.emit("closeEdit");
    };

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      uid: 0,
      realname: "",
      department: [],
      phone_country: "86",
      phone: "",
      work_phone: "",
      position: "",
      gender: "1",
      role_id: undefined,
      job_number: "",
      email: "",
      induction_time: undefined,
      avatar: "",
      work_name: "", // 职称
      birthday: undefined, // 出生年月
      political_type: undefined, // 政治面貌
      face_image: "",
    });
    const state = reactive({
      detail: {},
      activeKey: "basic",
      infoTabs: [
        {
          title: "基本信息",
          key: "basic",
        },
        {
          title: "工作信息",
          key: "work",
        },
        {
          title: "个人信息",
          key: "person",
        },
      ],
    });

    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      realname: [{ required: true, message: "成员姓名为必填项" }],
      phone: [{ required: true, message: "成员手机号码为必填项" }],
      department: [{ required: true, message: "所属部门为必选项" }],
    });

    const chooseMemberVisible = ref(false);
    const chooseMember = () => {
      chooseMemberVisible.value = true;
    };

    // 关闭选择成员弹窗
    const closeChooseMemberModal = () => {
      chooseMemberVisible.value = false;
    };

    // 成员选中
    const selectedMember = ref();
    const handleMemberSelect = (data) => {
      selectedMember.value = data.user[0];
      closeChooseMemberModal();
    };

    const handleTagClose = () => {
      selectedMember.value = null;
    };

    /**
     * @description: 手机号正则验证
     */
    const phoneFormat = (val, preVal) => {
      if (val && val.length > 11) {
        modelRef.phone = preVal;
        return;
      }
      if (val.length == 11 && !utils.phoneReg.test(val)) {
        message.error("请输入正确的手机号码！");
        return;
      }
      const reg = /^[0-9]*$/;
      if (reg.test(val)) {
        modelRef.phone = val;
      } else {
        modelRef.phone = preVal;
      }
    };
    watch(
      () => modelRef.phone,
      (phone, prePhone) => {
        phoneFormat(phone, prePhone);
      }
    );

    watch(
      () => store.getters.departmentList,
      (val) => {
        let _val = _.cloneDeep(val);
        if (!_val[0]?.is_direct_member) {
          _val[0].selectable = false;
        } else {
          _val[0].selectable = true;
        }
        departmentTreeData.value = _.cloneDeep(_val);
      }
    );

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      validate()
        .then(() => {
          let params = { ...toRaw(modelRef), needMsg: true };
          if (params.induction_time) {
            params.induction_time = params.induction_time.format("YYYY-MM-DD");
          }
          if (params.birthday) {
            params.birthday = params.birthday.format("YYYY-MM-DD");
          }
          params.department = params.department.length
            ? params.department.join(",")
            : undefined;
          if (selectedMember.value) {
            params.higher_uid = selectedMember.value.uid;
          }
          const success = (res) => {
            message.success(res.msg || "保存成功");
            context.emit("success", "member");
          };
          if (props.id) {
            params.uid = props.id;
            put("/org", "/department/user", params).then((res) => success(res));
          } else {
            post("/org", "/department/user", params).then((res) =>
              success(res)
            );
          }
        })
        .catch((err) => {
          console.log("error", err);
        });
    };

    /**
     * @description: 获取编辑信息
     */
    const departmentLabelArr = ref("");
    const getEditInfo = async () => {
      await get("/org", "/department/getUserDetail", { uid: props.id }).then(
        (res) => {
          const { list } = res;
          state.detail = list;
          setModelRef({
            uid: list.uid,
            realname: list.realname,
            department: list.departmentData
              ? list.departmentData.departmentIdsArr
              : [],
            phone: list.phone,
            work_phone: list.work_phone,
            position: list.position,
            gender: list.gender || "3",
            job_number: list.job_number,
            induction_time: list.induction_time
              ? moment(list.induction_time)
              : undefined,
            role_id: list.role_id || undefined,
            avatar: list.avatar,
            political_type: list.political_type || undefined,
            work_name: list.work_name,
            birthday: list.birthday ? moment(list.birthday) : undefined,
            email: list.email,
            face_image: list.face_image,
          });
          if (list.higher_uid) {
            selectedMember.value = {
              uid: list.higher_uid,
              realname: list.higher_username,
            };
          }
          if (props.type == "view") {
            departmentLabelArr.value = list.departmentData
              ? list.departmentData.labelTips
              : [];
          }
          fileList.value = [];
          if (list.avatar) {
            fileList.value = [
              {
                uid: "1",
                name: list.avatar,
                status: "done",
                url: list.avatar,
              },
            ];
          }
          filefaceImage.value = [];
          if (list.face_image) {
            filefaceImage.value = [
              {
                uid: "1",
                name: list.face_image,
                status: "done",
                url: list.face_image,
              },
            ];
          }
        }
      );
    };

    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      getRoleList();
      if (props.id) {
        getEditInfo();
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
          selectedMember.value = null;
          fileList.value = [];
          filefaceImage.value = [];
          state.detail = {};
          activeKey.value = "basic";
        }
      }
    );

    // 点击去编辑
    const toEdit = () => {
      modalType.value = "edit";
    };

    const getMemberGender = (gender) => {
      for (let item of genderOptions) {
        if (item.value == gender) {
          return item.label;
        }
      }
    };

    const roleList = ref([]);
    const getRoleList = () => {
      request.get("/org", "/department/role").then((res) => {
        roleList.value = res.list.map((item) => ({
          value: item.id,
          label: item.name,
        }));
      });
    };
    const getMemberRole = (id) => {
      if (id) {
        const current = roleList.value.find((item) => item.value == id);
        return current.label;
      } else {
        return "暂未分配角色";
      }
    };

    // 成员头像
    const fileList = ref([]);
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              modelRef.avatar = file.url;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        modelRef.avatar = "";
      }
      fileList.value = resFileList;
    };

    const activeKey = ref("basic");
    const filefaceImage = ref([]);
    const handleUploadFaceChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              modelRef.face_image = file.url;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        modelRef.face_image = "";
      }
      filefaceImage.value = resFileList;
    };

    const getName = (name) => {
      if (!name) return;
      if (name.length > 2) {
        return name.slice(-2);
      } else {
        return name;
      }
    };

    const getPolitical = (type) => {
      console.log(type, "88888");
      return politicalOptions.filter((a) => a.value == type)[0].label;
    };

    return {
      title,
      isAdmin,
      closeModal,
      validateInfos,
      resetFields,
      modelRef,
      onSubmit,
      departmentLabelArr,
      modalType,
      toEdit,
      genderOptions,
      getMemberGender,
      chooseMember,
      chooseMemberVisible,
      closeChooseMemberModal,
      handleMemberSelect,
      selectedMember,
      handleTagClose,
      roleList,
      getMemberRole,
      departmentTreeData,
      imgAction: request.BASE_URL + "/public/system/uploadImage",
      fileList,
      handleUploadChange,
      getName,
      ...toRefs(state),
      politicalOptions,
      getPolitical,
      disabledAdmin,
      activeKey,
      filefaceImage,
      handleUploadFaceChange,
    };
  },
});

const genderOptions = [
  { label: "男", value: "1" },
  { label: "女", value: "2" },
  { label: "未知", value: "3" },
];
const politicalOptions = [
  { label: "团员", value: 1 },
  { label: "党员", value: 2 },
  { label: "预备党员", value: 3 },
  { label: "无党派人士", value: 4 },
  { label: "群众", value: 5 },
];
</script>

<style lang="less" scoped>
.header-box {
  display: flex;
  margin-bottom: 10px;
}
.bg-primary {
  background-color: @primary-color;
  color: #fff;
  font-size: 16px;
}
.header-dec {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 10px;
  .dec-name {
    font-size: 16px;
    font-weight: bold;
    margin-right: 10px;
  }
  .dec-gray {
    padding-top: 5px;
    font-size: 14px;
    color: #6b6b6b;
  }
}
:deep(.ant-upload .ant-upload-select-picture-card) {
  width: 90px;
  height: 90px;
}
:deep(.ant-upload-list-picture-card-container){
  width: 90px;
  height: 90px;
}

</style>
